<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\Account as AccountModel;
use app\index\model\Paylist as PaylistModel;
use app\index\model\Withdrawlist as WithdrawModel;
use app\index\model\User as UserModel;
use app\index\model\Deallist as DLModel;
use app\index\model\Paylist as PLModel;
use app\index\model\Setting as STModel;
use think\Db;
use think\Session;



class Bill extends Base
{
    //账单首页
    public function index(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        // 更新积分
        $DLModel = new DLModel();
        $result = $DLModel->where('user_id', $UserID)->select();
        $deal_price = 0;
        $cpb = 0;
        $yhq = 0;
        $jf = 0;
        foreach ($result as $key => $value) {
            if ($value['status'] == 1) {
                $time = floor((time() - strtotime($value['create_time']))/3600/24);
                $i = floor($value['deal_price']/180);
                if ($time < 180) {
                    $cpb += $time*$i*1.5;
                    $yhq += $time*$i*0.5;
                    $jf += $value['deal_price'] - $time*$i*2;
                }else{
                    $cpb += $value['deal_price']*1.5;
                    $yhq += $value['deal_price']*0.5;
                    $jf += 0;
                }
            }
        }
        $AccountModel = new AccountModel();
        $Result = $AccountModel->save([
            'score' => $jf,
            'commodity_coin' => $cpb,
            'market_coin' => $yhq,
            'user_id' => $UserID
        ],['user_id' => $UserID]);

        //初始化模型

        $data = $AccountModel->where('user_id', $UserID)->find();
        $this->assign('data',$data);

        return $this->fetch();
    }

    //充值账单
    public function payIndex(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        $payList = new PaylistModel();
        
        //$data = $payList->where('userid', $UserID)->select();
        $data = $payList->order('create_time DESC')->paginate(10);
         //dump($data);die;
        
        $this->assign('data',$data);
       
        
         $page = $data->render();
         $total = $data->total();
         $count = $data->count();

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('total',$total);
        $this->assign('count',$count);
        return $this->fetch();
    }


    //充值申请页面展示
    public function payApply(){
        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);
        //$withDraw = input('post.');
        return $this->fetch();

    }

    //接收充值申请表单
    public function payApplyForm(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        $PayApplyInfo = input('post.');


        /*array(6) {

            ["payWay"] => string(1) "1"
            ["pay_name"] => string(3) "123"
            ["pay_reason"] => string(3) "123"
            ["pay_description"] => string(3) "123"
            ["pay_money"] => string(3) "123"
        }*/

        //存入数据库
        $UserPayList = new PLModel();
        $UserPayList->data([
            'userid' => $UserID,
            'pay_money' => $PayApplyInfo['pay_money'],
            'description' => $PayApplyInfo['pay_description'],
            'payname' => $PayApplyInfo['pay_name'],
            'type' => $PayApplyInfo['payWay']
        ]);
        $Reslut = $UserPayList->save();
        if($Reslut){
            $this->success("申请成功，等待审核中。。。");
        }else{
            $this->error('申请失败,请重试');
        }
    }

    //提现申请
    public function withDraw(){
        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);
        //$withDraw = input('post.');
        return $this->fetch();
    }

    public function withDrawForm(){
        $UserInfo = input('post.');
        
        $UserID = $UserInfo['User_id'];
        
        $UserAccount = new AccountModel();

        $UserAcountData = $UserAccount->where('user_id',$UserID)->find();


        /////////调取系统设置/////////////

        //实例化系统设置表
        $SystemSetting = new STModel();
        $SystemSettingData = $SystemSetting->where('id',1)->find();






        $UserCoin =$UserAcountData['gold_coin']/100*(100-$SystemSettingData['withdrawlist_percent']);
        if(!($UserInfo['pay_money'] < $UserCoin)){
            //要提现的钱大于账户的钱
            $this->error("你的账户没有这么多钱，无法提现，当前账户只能提取，扣除15%手续费之后的".$UserCoin."元");
        }
        //读取设置中的提现手续费比例




        //要收的手续费
        $theft = ($UserInfo['pay_money'] /100*$SystemSettingData['withdrawlist_percent']);
        //本次提现一共要收的钱
        $ListMoney = $UserInfo['pay_money'] + $theft;

        //新的账户金币余额
        $NewGoldCoin = $UserAcountData['gold_coin'] - $ListMoney;

        $ResltUpdateUserAccount = $UserAccount->save([
            'temp_money' => $ListMoney,
            'gold_coin' => $NewGoldCoin

        ],['user_id',$UserID]);

        if($ResltUpdateUserAccount){
            //提现申请成功
            $this->success("提现申请成功,等待审核!!!");
        }else{
            $this->error("提现申请失败！！！");
        }


        //提现表创建
        $Model = new WithdrawModel();

        $Result = $Model->data([
            'money' => $UserInfo['pay_money'],
            'bank_name' => $UserInfo['bank_name'],
            'bank_num' => $UserInfo['bank_num'],
            'bank_address' => $UserInfo['bank_address'],
            'reason' => $UserInfo['reason'],
            'description' => $UserInfo['description1'],
            'User_id' => $UserID
        ]);

        $Res = $Model->save();
        
        if($Result){
            //修改成功
             $this->success('成功');
            //echo 'sss';
        }else{
            //修改失败

            $this->error('修改失败',"Bill/index");
        }
    }

    //左右区展示
    public function block(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        //初始化模型

        //实例化 节点类
        //$BiNode = new \Core\BiNode();
        //取得所有设置过的数据
        $User  = new UserModel();
        $UserData = $User->where('pid_status','1')->select();

       // dumP($UserData);die;
        //得到整个树
        $FlushArr =  getChildrensID($UserData,$UserID);
        //dump($FlushArr);die;



        //取得直接的两个子ID
        $UserStraightChildID = $User->where([

            'pid_status' => ['EQ',1],
            'pid' => $UserID
        ])->select();

        //存两个直接子节点的数组
        $StraightID = array();
        foreach ($UserStraightChildID as $v){
            $StraightID[] =  $v['id'];
        }

        $StraightCount = count($StraightID);


        //大小区判断开始
        if($StraightCount < 2){
            //证明直接的子节点没有达到2个,所以不比较大小区
            $this->error("当前帐号推荐人有效订单少于2个，没有大小区！！！");
        }



        //先算左区
        $LeftChildList = getChildrensID($UserData,$StraightID[0]);

        //dump($LeftChildList);die;
        //存储左区总付款的变量
        $AllLeftMoney = 0;
        //实例化订单模型
        $DealList = new DLModel();
        foreach($LeftChildList as $singlelistV){

            $Leftprice = $DealList->where([

                'status' => ['EQ',1],
                'User_id'=> $singlelistV,
                'tree_status'=> '1'
            ])->select();

            foreach($Leftprice as $singleV){
                $AllLeftMoney += $singleV['deal_price'];
            }
        }

        //算右区
        $RightChildList = getChildrensID($UserData,$StraightID[1]);

        //dump($RightChildList);die;
        //存储右区总付款的变量
        $AllRightMoney = 0;
        //实例化订单模型
        $DealList = new DLModel();
        foreach($RightChildList as $singlelistV){

            $Rightprice = $DealList->where([

                'status' => ['EQ',1],
                'User_id'=> $singlelistV,
                'tree_status'=> '1'
            ])->select();

            foreach($Rightprice as $singleV){
                $AllRightMoney += $singleV['deal_price'];
            }
        }
        //echo $AllRightMoney;die;
        $this->assign('left_block',$AllLeftMoney);
        $this->assign('right_block',$AllRightMoney);

        return $this->fetch();
    }

    //利润展示
    public function profit(){

        $UserID = Session::get('userid');
        $UserName = Session::get('username');
        //echo $UserID;
        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);

        $UserAccount = new AccountModel();

        $data = $UserAccount->where('user_id',$UserID)->find();
        //dump($data);die;
        $this->assign('data',$data);

        return $this->fetch();
    }
}
